package br.com.Login.controller.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import br.com.Login.controller.SessaoUserInterface;

public class FiltroAcessoLogin implements Filter{

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		try{
			SessaoUserInterface u = (SessaoUserInterface)Class.forName(request.getServletContext().getInitParameter("sessao_usuario")).newInstance(); 
			if(u == null || u.getUser() == null || u.getLoggedin() == false){
				chain.doFilter(request, response);

			}else if(u.getLoggedin() == true){
				String contextPath = request.getServletContext().getContextPath();
				HttpServletResponse r = (HttpServletResponse) response;
				r.sendRedirect(contextPath+"/pages/index.xhtml");
			}
			}catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub	
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub		
	}	
}
